import pytest
from appium.common.logger import logger
from appium.webdriver.common.appiumby import AppiumBy

from base.wecom_app import WeComApp
from page.address_list_page import AddressListPage


class AddressListSearchPage(WeComApp):
    _SEARCH_BOX = AppiumBy.XPATH, "//*[@class='android.widget.EditText']"
    _SEARCH_RESULT = AppiumBy.XPATH, "//*[@text='联系人']/../following-sibling::*//*[@class='android.widget.TextView']"
    _BACK_BTN = AppiumBy.XPATH, "//*[@class='android.widget.TextView']"

    def search_and_get_result(self, keyword):

        logger.info("【搜索框】输入关键字")
        self.wait_for_click(*self._SEARCH_BOX)
        self.find_and_sendkeys(keyword, *self._SEARCH_BOX)

        logger.info("获取搜索结果")
        text = self.find_and_get_text(*self._SEARCH_RESULT)
        return text

    def search_and_click_first_person(self, keyword):

        logger.info("【搜索框】输入关键字")
        self.wait_for_click(*self._SEARCH_BOX)
        self.find_and_sendkeys(keyword, *self._SEARCH_BOX)

        # 点击第一个联系人
        # 确认是否有搜索结果
        exists = self.wait_for_text('联系人')

        if not exists:
            pytest.xfail(reason=f"{keyword}：无搜索结果")

        logger.info("获取搜索结果元素")
        res = self.finds(*self._SEARCH_RESULT)

        self.count_old = len(res)
        print(f'count_old={self.count_old}')
        # 搜索结果元素text与需删除姓名对比
        if res[0].text != keyword:
            pytest.xfail(reason=f"{keyword}：与搜索结果{res[0].text}不匹配")
        else:
            logger.info(f"{keyword}搜索结果匹配")

        # 点击搜索结果
        res[0].click()

        # 进入个人信息页
        from page.person_information_page import PersonInformationPage
        return PersonInformationPage(self.driver)

    def gobackto_address_list_page(self):
        logger.info("点击【返回】按钮")
        self.find_and_click(*self._BACK_BTN)
        return AddressListPage(self.driver)

    def search_not_exist_and_get_result(self, keyword):

        logger.info("【搜索框】输入关键字")
        self.wait_for_click(*self._SEARCH_BOX)
        self.find_and_sendkeys(keyword, *self._SEARCH_BOX)
        # 获取搜索结果
        # 如果没有联系人，则删除成功
        exists = self.wait_for_text('联系人')
        if not exists:
            return True
        else:
            text = self.find_and_get_text(*self._SEARCH_RESULT)
        return text != keyword
